package com.kyrioscraft.cloud.thead.jdklab.tools.reentrant;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author kyrioscraft
 * @Date 2019/2/14 15:17
 * @Description //TODO
 **/
public class LockInterruptDemo implements Runnable{

    public static ReentrantLock lock1 = new ReentrantLock();
    public static ReentrantLock lock2 = new ReentrantLock();
    int lock;
    public LockInterruptDemo(int lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        try{
            if(lock==1){
                lock1.lockInterruptibly();
                try {
                    Thread.sleep(500);
                }catch (InterruptedException e){

                }
                lock2.lockInterruptibly();
            } else {
                lock2.lockInterruptibly();
                try {
                    Thread.sleep(500);
                }catch (InterruptedException e){

                }
                lock1.lockInterruptibly();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if(lock1.isHeldByCurrentThread()) {
                lock1.unlock();
            }
            if(lock2.isHeldByCurrentThread()) {
                lock2.unlock();
            }
            System.out.println(Thread.currentThread().getId()+":线程退出");
        }
    }

    public static void main(String[] args) throws Exception{
        LockInterruptDemo r1 = new LockInterruptDemo(1);
        LockInterruptDemo r2 = new LockInterruptDemo(2);
        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);
        t1.start();
        t2.start();
        Thread.sleep(1000);
        t2.interrupt();
    }
}
